import { takeEvery } from 'redux-saga';
import { put, call } from 'redux-saga/effects'
import {
  LOAD,
  LOAD_SUCCESS,
  LOAD_FAIL,
  LOAD_WITH_TOKEN,
  LOGIN,
  LOGIN_SUCCESS,
  LOGIN_FAIL,
  LOGOUT,
  LOGOUT_SUCCESS,
  LOGOUT_FAIL,
  REGISTER,
  REGISTER_SUCCESS,
  REGISTER_FAIL
} from './constants';
import {ax_post, ax_get} from '../../utils/ax_agent'
import jscookie from 'js-cookie'

export default function* appSaga() {
  yield [
    catchLogin(),
    catchLoadWithToken(),
    catchLogout(),
    catchRegister()
  ]
}



/*
  Catch Login Action
*/
function* catchLogin() {
  yield* takeEvery( LOAD, loginUser)
}

function* loginUser(action) {
   try {
      const result = yield call( ax_post,  '/auth/local', {email: action.email, password: action.password} )
      
      yield put({type: LOAD_SUCCESS, result: result.data.user});

      yield jscookie.set('app_user_token', result.data.token)

   } catch (e) {
      yield put({type: LOAD_FAIL, message: e.message});
   }
}

/*
  Catch Load Auth with Token Action
*/
function* catchLoadWithToken() {
  yield* takeEvery( LOAD_WITH_TOKEN, loadWithToken)
}

function* loadWithToken(action) {
   try {
      const result = yield call( ax_get,  '/api/user/me',  
        { headers: {  'Authorization': 'Bearer ' + jscookie.get('app_user_token')  } }   )

      if (result.err) throw "load fail"

      yield put({type: LOAD_SUCCESS, result: result.data});

   } catch (err) {
      yield put({type: LOAD_FAIL, message: err});
   }
}



/*
  Catch Logout Action
*/
function* catchLogout() {
  yield* takeEvery( LOGOUT, logout)
}

function* logout(action) {
   try {
      yield jscookie.remove('app_user_token');

      yield put({type: LOGOUT_SUCCESS});

   } catch (e) {
      yield put({type: LOGOUT_FAIL, message: e.message});
   }
}

/*
  Catch Register Action
*/
function* catchRegister() {
  yield* takeEvery( REGISTER, register)
}

function* register(action) {
   try {
      const result = yield call( ax_post,  '/api/user', {name: action.username, email: action.email, password: action.password} )
      
      yield put({type: REGISTER_SUCCESS, result: result.data.user});

      yield jscookie.set('app_user_token', result.data.token)

   } catch (e) {
      yield put({type: REGISTER_FAIL, message: e.message});
   }
}






